<template>
  <div class="books-types">
    <div
      class="item"
      v-for="item in unfoldTypes"
      :key="item.typeId"
      :class="{ active: item.typeId === chooseId }"
      @click="chooseType(item.typeId)"
    >
      <span class="name">{{ item.typeName }}</span>
    </div>
    <a href="" @click.prevent="unfold = !unfold">{{
      unfold ? "折叠" : "展开"
    }}</a>
  </div>
</template>

<script>
import { getBookTypes } from "@/services/BooksService.js";
export default {
  data() {
    return {
      types: [],
      unfold: false,
      chooseId: null,
    };
  },
  async created() {
    console.log("界面创建了");
    let resp = await getBookTypes();
    console.log(resp);
    this.types = resp;
     // 默认选择第一个
    this.chooseType(this.types[0].typeId);
  },
  // 计算属性 折叠 展开
  computed: {
    unfoldTypes() {
      if (this.unfold) {
        return this.types;
      } else {
        return this.types.slice(0, 3);
      }
    },
  },
  // 方法区
  methods: {
    chooseType(typeId) {
      this.chooseId = typeId;
      // 跨界面传值两部曲
      // 1.注册事件$emit 子组件调用父组件的方法并传递数据
      // 子组件chooseType事件触发后，自动触发父组件catchType事件
      this.$emit("changeType", this.chooseId);
    },
  },
};
</script>

<style scoped>
.books-types {
  margin: 30px 0;
  border-bottom: 1px solid #ccc;
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
  padding-bottom: 15px;
}
.item {
  padding: 10px 20px;
  border-radius: 5px;
  border: 1px solid #ccc;
  margin-right: 15px;
  margin: 7px 15px 7px 0;
  cursor: pointer;
  position: relative;
}
.item:hover {
  background: #ccc;
}
.item.active {
  background: #000;
  color: #fff;
}
.books-types a {
  align-self: flex-end;
  margin-bottom: 20px;
  color: #409eff;
}
</style>
